//
//  EWFriendViewController.m
//  haveSomethingToEat
//
//  Created by 陈宁权 on 2017/4/8.
//  Copyright © 2017年 陈 宁权. All rights reserved.
//

#import "EWFriendViewController.h"
#import "KxMenu.h"
#import "RCDSearchFriendViewController.h"
#import "RCDContactViewController.h"
#import "RCDContactSelectedTableViewController.h"
#import "RCDSearchBar.h"
#import "UIColor+RCColor.h"
#import "RCDSearchViewController.h"
#import "RCDChatViewController.h"
#import "RCDAddressBookViewController.h"
#import "RCDChatListCell.h"
#import "RCDUserInfo.h"
#import "EWUserInfo.h"

@interface EWFriendViewController ()<UISearchBarDelegate,RCDSearchViewDelegate>
@property (nonatomic,strong)UINavigationController *searchNavigationController;
@property (nonatomic,strong)UIView *headerView;
@property (nonatomic,strong)RCDSearchBar *searchBar;
@property(nonatomic, strong) RCConversationModel *tempModel;

@property(nonatomic, assign) NSUInteger index;

@property(nonatomic, assign) BOOL isClick;
- (void)updateBadgeValueForTabBarItem;
@end

@implementation EWFriendViewController
{
    UIImageView *navBarHairlineImageView;
}

- (RCDSearchBar *)searchBar{
    if (!_searchBar) {
        _searchBar = [[RCDSearchBar alloc] initWithFrame:CGRectMake(0, 0, self.conversationListTableView.frame.size.width, 44)];
        
    }
    return _searchBar;
}

- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.conversationListTableView.frame.size.width, 44)];
    }
    return _headerView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //配置导航栏
    [self configNav];
    
    navBarHairlineImageView = [self findHairlineImageViewUnder:self.navigationController.navigationBar];
    
    self.view.backgroundColor = [UIColor clearColor];
    //设置需要显示哪些类型的会话
    [self setDisplayConversationTypes:@[@(ConversationType_PRIVATE),
                                        @(ConversationType_DISCUSSION),
                                        @(ConversationType_CHATROOM),
                                        @(ConversationType_GROUP),
                                        @(ConversationType_APPSERVICE),
                                        @(ConversationType_SYSTEM)]];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationController.navigationBar.translucent = NO;
    self.searchBar.delegate = self;
    [self.headerView addSubview:self.searchBar];
    self.conversationListTableView.tableHeaderView = self.headerView;
    
    //设置tableView样式
    self.conversationListTableView.separatorColor =
    [UIColor colorWithHexString:@"dfdfdf" alpha:1.0f];
    self.conversationListTableView.tableFooterView = [UIView new];
    
    // 设置在NavigatorBar中显示连接中的提示
    self.showConnectingStatusOnNavigatorBar = YES;
    
    //定位未读数会话
    self.index = 0;
    //接收定位到未读数会话的通知
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(GotoNextCoversation)
     name:@"GotoNextCoversation"
     object:nil];
    
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(updateForSharedMessageInsertSuccess)
     name:@"RCDSharedMessageInsertSuccess"
     object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(refreshCell:)
                                                 name:@"RefreshConversationList"
                                               object:nil];
    
}

- (UIImageView *)findHairlineImageViewUnder:(UIView *)view {
    if ([view isKindOfClass:UIImageView.class] && view.bounds.size.height <= 1.0) {
        return (UIImageView *)view;
    }
    for (UIView *subview in view.subviews) {
        UIImageView *imageView = [self findHairlineImageViewUnder:subview];
        if (imageView) {
            return imageView;
        }
    }
    return nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.hidden = NO;
    navBarHairlineImageView.hidden = YES;
    _isClick = YES;
    
    //  [self notifyUpdateUnreadMessageCount];
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(receiveNeedRefreshNotification:)
     name:@"kRCNeedReloadDiscussionListNotification"
     object:nil];
    RCUserInfo *groupNotify = [[RCUserInfo alloc] initWithUserId:@"__system__"
                                                            name:@""
                                                        portrait:nil];
    [[RCIM sharedRCIM] refreshUserInfoCache:groupNotify withUserId:@"__system__"];
}

//由于demo使用了tabbarcontroller，当切换到其它tab时，不能更改tabbarcontroller的标题。
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    navBarHairlineImageView.hidden = NO;
    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:@"kRCNeedReloadDiscussionListNotification"
     object:nil];
    
}

- (void)updateBadgeValueForTabBarItem {
    __weak typeof(self) __weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        int count = [[RCIMClient sharedRCIMClient]
                     getUnreadCount:self.displayConversationTypeArray];
        if (count > 0) {
              __weakSelf.tabBarItem.badgeValue = [[NSString alloc] initWithFormat:@"%d", count];
        } else {
              __weakSelf.tabBarItem.badgeValue = nil;
        }
    });
}

//重写RCConversationListViewController的onSelectedTableRow事件
- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType
         conversationModel:(RCConversationModel *)model
               atIndexPath:(NSIndexPath *)indexPath {
    if (_isClick) {
        _isClick = NO;
        if (model.conversationModelType ==
            RC_CONVERSATION_MODEL_TYPE_PUBLIC_SERVICE) {
            RCDChatViewController *_conversationVC =
            [[RCDChatViewController alloc] init];
            _conversationVC.conversationType = model.conversationType;
            _conversationVC.targetId = model.targetId;
            _conversationVC.title = model.conversationTitle;
            _conversationVC.conversation = model;
            [self.navigationController pushViewController:_conversationVC
                                                 animated:YES];
        }
        
        if (conversationModelType == RC_CONVERSATION_MODEL_TYPE_NORMAL) {
            RCDChatViewController *_conversationVC =
            [[RCDChatViewController alloc] init];
            _conversationVC.conversationType = model.conversationType;
            _conversationVC.targetId = model.targetId;
            _conversationVC.title = model.conversationTitle;
            _conversationVC.conversation = model;
            _conversationVC.unReadMessage = model.unreadMessageCount;
            _conversationVC.enableNewComingMessageIcon = YES; //开启消息提醒
            _conversationVC.enableUnreadMessageIcon = YES;
            if (model.conversationType == ConversationType_SYSTEM) {
                _conversationVC.title = @"系统消息";
            }
            if ([model.objectName isEqualToString:@"RC:ContactNtf"]) {
                RCDAddressBookViewController * addressBookVC= [RCDAddressBookViewController addressBookViewController];
                addressBookVC.needSyncFriendList = YES;
                
                [self.navigationController pushViewController:addressBookVC
                                                     animated:YES];
                return;
            }
            //如果是单聊，不显示发送方昵称
            if (model.conversationType == ConversationType_PRIVATE) {
                _conversationVC.displayUserNameInCell = YES;
            }
            [self.navigationController pushViewController:_conversationVC
                                                 animated:YES];
        }
        
        //聚合会话类型，此处自定设置。
        if (conversationModelType == RC_CONVERSATION_MODEL_TYPE_COLLECTION) {
            
            
            
        }
        
        //自定义会话类型
        if (conversationModelType == RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION) {
            RCConversationModel *model =
            self.conversationListDataSource[indexPath.row];
            
            if ([model.objectName isEqualToString:@"RC:ContactNtf"]) {
                RCDAddressBookViewController * addressBookVC= [RCDAddressBookViewController addressBookViewController];
                [self.navigationController pushViewController:addressBookVC
                                                     animated:YES];
            }
        }
    }
    dispatch_after(
                   dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)),
                   dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                       [self refreshConversationTableViewIfNeeded];
                   });
    //刷新tabbar的未读消息数
    [self notifyUpdateUnreadMessageCount];
}

- (void)configNav
{
    
    
    [self.navigationItem setTitle:@"朋友"];
    
    UIButton *contactBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [contactBtn setBackgroundImage:[UIImage imageNamed:@"icon_Contacts"] forState:UIControlStateNormal];
    [contactBtn addTarget:self action:@selector(showContact) forControlEvents:UIControlEventTouchUpInside];
    contactBtn.frame = CGRectMake(0, 0, 17, 17);
    UIBarButtonItem *contactItem = [[UIBarButtonItem alloc] initWithCustomView:contactBtn];
    
    UIButton *addFriendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addFriendBtn setBackgroundImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [addFriendBtn addTarget:self action:@selector(addFriend:) forControlEvents:UIControlEventTouchUpInside];
    addFriendBtn.frame = CGRectMake(0, 0, 15, 15);
    UIBarButtonItem *addItem = [[UIBarButtonItem alloc] initWithCustomView:addFriendBtn];
    
    self.navigationItem.rightBarButtonItems = @[addItem,contactItem];
}

- (void)showContact
{
    RCDContactViewController *contactVC = [[RCDContactViewController alloc] init];
    contactVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:contactVC animated:YES];
}

- (void)addFriend:(UIButton *)sender
{
    NSArray *menuItems = @[
                           
                           [KxMenuItem menuItem:@"发起聊天"
                                          image:[UIImage imageNamed:@"chat"]
                                         target:self
                                         action:@selector(pushChat:)],
                           
                           [KxMenuItem menuItem:@"创建群组"
                                          image:[UIImage imageNamed:@"group"]
                                         target:self
                                         action:@selector(pushContactSelected:)],
                           
                           [KxMenuItem menuItem:@"添加好友"
                                          image:[UIImage imageNamed:@"add_friends"]
                                         target:self
                                         action:@selector(pushAddFriend:)],

//                           [KxMenuItem menuItem:@"创建讨论组"
//                                          image:[UIImage imageNamed:@"addfriend_icon"]
//                                         target:self
//                                         action:@selector(pushToCreateDiscussion:)],

                           ];
    
    [KxMenu setTintColor:[UIColor blackColor]];
    [KxMenu setTitleFont:[UIFont systemFontOfSize:17]];
    [KxMenu showMenuInView:self.navigationController
     .navigationBar.superview
                  fromRect:sender.frame
                 menuItems:menuItems];
}

/**
 *  发起聊天
 *
 *  @param sender sender description
 */
- (void)pushChat:(id)sender
{
    RCDContactSelectedTableViewController *contactSelectedVC = [[RCDContactSelectedTableViewController alloc]init];
    //    contactSelectedVC.forCreatingDiscussionGroup = YES;
    contactSelectedVC.isAllowsMultipleSelection = NO;
    contactSelectedVC.titleStr = @"发起聊天";
    contactSelectedVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:contactSelectedVC animated:YES];
}

/**
 *  创建群组
 *
 *  @param sender sender description
 */
- (void)pushContactSelected:(id)sender
{
    RCDContactSelectedTableViewController *contactSelectedVC = [[RCDContactSelectedTableViewController alloc]init];
    contactSelectedVC.forCreatingGroup = YES;
    contactSelectedVC.isAllowsMultipleSelection = YES;
    contactSelectedVC.titleStr = @"选择联系人";
    contactSelectedVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:contactSelectedVC animated:YES];
}

/**
 *  添加好友
 *
 *  @param sender sender description
 */
- (void)pushAddFriend:(id)sender
{
    RCDSearchFriendViewController *searchFirendVC =
    [RCDSearchFriendViewController searchFriendViewController];
    [self.navigationController pushViewController:searchFirendVC animated:YES];
}

/**
 *  创建讨论组
 *
 *  @param sender sender description
 */
- (void)pushToCreateDiscussion:(id)sender
{
    NSLog(@"pushToCreateDiscussion");
    RCDContactSelectedTableViewController * contactSelectedVC= [[RCDContactSelectedTableViewController alloc]init];
    contactSelectedVC.forCreatingDiscussionGroup = YES;
    contactSelectedVC.isAllowsMultipleSelection = YES;
    contactSelectedVC.titleStr = @"选择联系人";
    contactSelectedVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:contactSelectedVC animated:YES];
}


//*********************插入自定义Cell*********************//

//插入自定义会话model
- (NSMutableArray *)willReloadTableData:(NSMutableArray *)dataSource {
    
    for (int i = 0; i < dataSource.count; i++) {
        RCConversationModel *model = dataSource[i];
        //筛选请求添加好友的系统消息，用于生成自定义会话类型的cell
        if (model.conversationType == ConversationType_SYSTEM &&
            [model.lastestMessage
             isMemberOfClass:[RCContactNotificationMessage class]]) {
                model.conversationModelType = RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
            }
        if ([model.lastestMessage
             isKindOfClass:[RCGroupNotificationMessage class]]) {
            RCGroupNotificationMessage *groupNotification =
            (RCGroupNotificationMessage *)model.lastestMessage;
            if ([groupNotification.operation isEqualToString:@"Quit"]) {
                NSData *jsonData =
                [groupNotification.data dataUsingEncoding:NSUTF8StringEncoding];
                NSDictionary *dictionary = [NSJSONSerialization
                                            JSONObjectWithData:jsonData
                                            options:NSJSONReadingMutableContainers
                                            error:nil];
                NSDictionary *data =
                [dictionary[@"data"] isKindOfClass:[NSDictionary class]]
                ? dictionary[@"data"]
                : nil;
                NSString *nickName =
                [data[@"operatorNickname"] isKindOfClass:[NSString class]]
                ? data[@"operatorNickname"]
                : nil;
                if ([nickName isEqualToString:[RCIM sharedRCIM].currentUserInfo.name]) {
                    [[RCIMClient sharedRCIMClient]
                     removeConversation:model.conversationType
                     targetId:model.targetId];
                    [self refreshConversationTableViewIfNeeded];
                }
            }
        }
    }
    
    return dataSource;
}

//左滑删除
- (void)rcConversationListTableView:(UITableView *)tableView
                 commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
                  forRowAtIndexPath:(NSIndexPath *)indexPath {
    //可以从数据库删除数据
    RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    [[RCIMClient sharedRCIMClient] removeConversation:ConversationType_SYSTEM
                                             targetId:model.targetId];
    [self.conversationListDataSource removeObjectAtIndex:indexPath.row];
    [self.conversationListTableView reloadData];
}

//高度
- (CGFloat)rcConversationListTableView:(UITableView *)tableView
               heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 67.0f;
}

//自定义cell
- (RCConversationBaseCell *)rcConversationListTableView:(UITableView *)tableView
                                  cellForRowAtIndexPath:
(NSIndexPath *)indexPath {
    RCConversationModel *model = self.conversationListDataSource[indexPath.row];
    
    __block NSString *userName = nil;
    __block NSString *portraitUri = nil;
    RCContactNotificationMessage *_contactNotificationMsg = nil;
    
    __weak EWFriendViewController *weakSelf = self;
    //此处需要添加根据userid来获取用户信息的逻辑，extend字段不存在于DB中，当数据来自db时没有extend字段内容，只有userid
    if (nil == model.extend) {
        // Not finished yet, To Be Continue...
        if (model.conversationType == ConversationType_SYSTEM &&
            [model.lastestMessage
             isMemberOfClass:[RCContactNotificationMessage class]]) {
                _contactNotificationMsg =
                (RCContactNotificationMessage *)model.lastestMessage;
                if (_contactNotificationMsg.sourceUserId == nil) {
                    RCDChatListCell *cell =
                    [[RCDChatListCell alloc] initWithStyle:UITableViewCellStyleDefault
                                           reuseIdentifier:@""];
                    cell.lblDetail.text = @"好友请求";
                    [cell.ivAva sd_setImageWithURL:[NSURL URLWithString:portraitUri]
                                  placeholderImage:[UIImage imageNamed:@"system_notice"]];
                    return cell;
                }
                NSDictionary *_cache_userinfo = [[NSUserDefaults standardUserDefaults]
                                                 objectForKey:_contactNotificationMsg.sourceUserId];
                if (_cache_userinfo) {
                    userName = _cache_userinfo[@"username"];
                    portraitUri = _cache_userinfo[@"portraitUri"];
                } else {
                    NSDictionary *emptyDic = @{};
                    [[NSUserDefaults standardUserDefaults]
                     setObject:emptyDic
                     forKey:_contactNotificationMsg.sourceUserId];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    
                    [[BQUserDao shareObject] queryUserInfoWithUserId:_contactNotificationMsg.sourceUserId andServiceReceiveResponseSuccess:^(id response) {
                        EWUserInfo *user = [EWUserInfo mj_objectWithKeyValues:response[@"user"]];
                        if (user == nil) {
                            return;
                        }
                        RCDUserInfo *rcduserinfo_ = [RCDUserInfo new];
                        rcduserinfo_.name = user.userName;
                        userName = user.userName;
                        rcduserinfo_.userId = user.userId;
                        rcduserinfo_.portraitUri = user.portraitUri;
                        
                        model.extend = rcduserinfo_;
                        
                        // local cache for userInfo
                        NSDictionary *userinfoDic = @{
                                                      @"username" : rcduserinfo_.name,
                                                      @"portraitUri" : rcduserinfo_.portraitUri
                                                      };
                        [[NSUserDefaults standardUserDefaults]
                         setObject:userinfoDic
                         forKey:_contactNotificationMsg.sourceUserId];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        
                        [weakSelf.conversationListTableView
                         reloadRowsAtIndexPaths:@[ indexPath ]
                         withRowAnimation:
                         UITableViewRowAnimationAutomatic];
                        
                    } ServiceReceiveResponseFailed:^(id response) {
                        NSLog(@"获取用户信息失败");
                    }];
                    
                }
            }
        
    } else {
        RCDUserInfo *user = (RCDUserInfo *)model.extend;
        userName = user.name;
        portraitUri = user.portraitUri;
    }
    
    RCDChatListCell *cell =
    [[RCDChatListCell alloc] initWithStyle:UITableViewCellStyleDefault
                           reuseIdentifier:@""];
    NSString *operation = _contactNotificationMsg.operation;
    NSString *operationContent;
    if ([operation isEqualToString:@"Request"]) {
        operationContent = [NSString stringWithFormat:@"来自%@的好友请求", userName];
    } else if ([operation isEqualToString:@"AcceptResponse"]) {
        operationContent = [NSString stringWithFormat:@"%@通过了你的好友请求", userName];
    }
    cell.lblDetail.text = operationContent;
    [cell.ivAva sd_setImageWithURL:[NSURL URLWithString:portraitUri]
                  placeholderImage:[UIImage imageNamed:@"system_notice"]];
    cell.labelTime.text = [RCKitUtility ConvertMessageTime:model.sentTime/1000];
    cell.model = model;
    return cell;
}

//*********************插入自定义Cell*********************//

#pragma mark - 收到消息监听
- (void)didReceiveMessageNotification:(NSNotification *)notification {
    __weak typeof(&*self) blockSelf_ = self;
    //处理好友请求
    RCMessage *message = notification.object;
    if ([message.content isMemberOfClass:[RCContactNotificationMessage class]]) {
        
        if (message.conversationType != ConversationType_SYSTEM) {
            NSLog(@"好友消息要发系统消息！！！");
#if DEBUG
            @throw [[NSException alloc]
                    initWithName:@"error"
                    reason:@"好友消息要发系统消息！！！"
                    userInfo:nil];
#endif
        }
        RCContactNotificationMessage *_contactNotificationMsg =
        (RCContactNotificationMessage *)message.content;
        if (_contactNotificationMsg.sourceUserId == nil ||
            _contactNotificationMsg.sourceUserId.length == 0) {
            return;
        }
        //该接口需要替换为从消息体获取好友请求的用户信息
        [[BQUserDao shareObject] queryUserInfoWithUserId:_contactNotificationMsg.sourceUserId andServiceReceiveResponseSuccess:^(id response) {
            
            EWUserInfo *user = [EWUserInfo mj_objectWithKeyValues:response[@"user"]];
            RCDUserInfo *rcduserinfo_ = [RCDUserInfo new];
            rcduserinfo_.name = user.userName;
            rcduserinfo_.userId = user.userId;
            rcduserinfo_.portraitUri = user.portraitUri;
            
            RCConversationModel *customModel = [RCConversationModel new];
            customModel.conversationModelType =
            RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION;
            customModel.extend = rcduserinfo_;
            customModel.conversationType = message.conversationType;
            customModel.targetId = message.targetId;
            customModel.sentTime = message.sentTime;
            customModel.receivedTime = message.receivedTime;
            customModel.senderUserId = message.senderUserId;
            customModel.lastestMessage = _contactNotificationMsg;
            //[_myDataSource insertObject:customModel atIndex:0];
            
            // local cache for userInfo
            NSDictionary *userinfoDic = @{
                                          @"username" : rcduserinfo_.name,
                                          @"portraitUri" : rcduserinfo_.portraitUri
                                          };
            [[NSUserDefaults standardUserDefaults]
             setObject:userinfoDic
             forKey:_contactNotificationMsg.sourceUserId];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                //调用父类刷新未读消息数
                [blockSelf_
                 refreshConversationTableViewWithConversationModel:
                 customModel];
                [self notifyUpdateUnreadMessageCount];
                
                //当消息为RCContactNotificationMessage时，没有调用super，如果是最后一条消息，可能需要刷新一下整个列表。
                //原因请查看super didReceiveMessageNotification的注释。
                NSNumber *left =
                [notification.userInfo objectForKey:@"left"];
                if (0 == left.integerValue) {
                    [super refreshConversationTableViewIfNeeded];
                }
            });

        } ServiceReceiveResponseFailed:^(id response) {
            
        }];
    }
    else if([message.content isMemberOfClass:[RCCommandMessage class]]){
        RCCommandMessage *msg = (RCCommandMessage *)message.content;
        if ([msg.name isEqualToString:@"UpdateUserInfo"]) {
            [super refreshConversationTableViewIfNeeded];
        }
    }
    else
    {
        //调用父类刷新未读消息数
        [super didReceiveMessageNotification:notification];
    }
}
- (void)didTapCellPortrait:(RCConversationModel *)model {
    if (model.conversationModelType ==
        RC_CONVERSATION_MODEL_TYPE_PUBLIC_SERVICE) {
        RCDChatViewController *_conversationVC =
        [[RCDChatViewController alloc] init];
        _conversationVC.conversationType = model.conversationType;
        _conversationVC.targetId = model.targetId;
        _conversationVC.title = model.conversationTitle;
        _conversationVC.conversation = model;
        _conversationVC.unReadMessage = model.unreadMessageCount;
        [self.navigationController pushViewController:_conversationVC animated:YES];
    }
    
    if (model.conversationModelType == RC_CONVERSATION_MODEL_TYPE_NORMAL) {
        RCDChatViewController *_conversationVC =
        [[RCDChatViewController alloc] init];
        _conversationVC.conversationType = model.conversationType;
        _conversationVC.targetId = model.targetId;
        _conversationVC.title = model.conversationTitle;
        _conversationVC.conversation = model;
        _conversationVC.unReadMessage = model.unreadMessageCount;
        _conversationVC.enableNewComingMessageIcon = YES; //开启消息提醒
        _conversationVC.enableUnreadMessageIcon = YES;
        if (model.conversationType == ConversationType_SYSTEM) {
            _conversationVC.title = @"系统消息";
        }
        if ([model.objectName isEqualToString:@"RC:ContactNtf"]) {
            RCDAddressBookViewController *addressBookVC = [RCDAddressBookViewController addressBookViewController];
            addressBookVC.needSyncFriendList = YES;
            [self.navigationController pushViewController:addressBookVC animated:YES];
            return;
        }
        //如果是单聊，不显示发送方昵称
        if (model.conversationType == ConversationType_PRIVATE) {
            _conversationVC.displayUserNameInCell = NO;
        }
        [self.navigationController pushViewController:_conversationVC animated:YES];
    }
    
    //聚合会话类型，此处自定设置。
    if (model.conversationModelType == RC_CONVERSATION_MODEL_TYPE_COLLECTION) {
        
        
    }
    
    //自定义会话类型
    if (model.conversationModelType == RC_CONVERSATION_MODEL_TYPE_CUSTOMIZATION) {
        //        RCConversationModel *model =
        //        self.conversationListDataSource[indexPath.row];
        
        if ([model.objectName isEqualToString:@"RC:ContactNtf"]) {
            RCDAddressBookViewController *addressBookVC = [RCDAddressBookViewController addressBookViewController];
            [self.navigationController pushViewController:addressBookVC animated:YES];
        }
    }
}

 //会话有新消息通知的时候显示数字提醒，设置为NO,不显示数字只显示红点
//- (void)willDisplayConversationTableCell:(RCConversationBaseCell *)cell
// atIndexPath:(NSIndexPath *)indexPath
//{
//     RCConversationModel *model= self.conversationListDataSource[indexPath.row];
//     if (model.conversationType == ConversationType_PRIVATE)
//     {
//         ((RCConversationCell *)cell).isShowNotificationNumber = NO;
//     }
//}

- (void)notifyUpdateUnreadMessageCount {
    [self updateBadgeValueForTabBarItem];
}

- (void)receiveNeedRefreshNotification:(NSNotification *)status {
    __weak typeof(&*self) __blockSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        if (__blockSelf.displayConversationTypeArray.count == 1 &&
            [self.displayConversationTypeArray[0] integerValue] ==
            ConversationType_DISCUSSION) {
            [__blockSelf refreshConversationTableViewIfNeeded];
        }
        
    });
}

- (void)scrollViewDidScroll:(UIScrollView*)scrollView
{
    NSIndexPath *indexPath = [self.conversationListTableView indexPathForRowAtPoint:scrollView.contentOffset];
    self.index = indexPath.row;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    //恢复conversationListTableView的自动回滚功能。
    self.conversationListTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

-(void) GotoNextCoversation
{
    NSUInteger i;
    //设置contentInset是为了滚动到底部的时候，避免conversationListTableView自动回滚。
    self.conversationListTableView.contentInset = UIEdgeInsetsMake(0, 0, self.conversationListTableView.frame.size.height, 0);
    for (i = self.index + 1; i < self.conversationListDataSource.count; i++) {
        RCConversationModel *model = self.conversationListDataSource[i];
        if (model.unreadMessageCount > 0) {
            NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
            self.index = i;
            [self.conversationListTableView scrollToRowAtIndexPath:scrollIndexPath
                                                  atScrollPosition:UITableViewScrollPositionTop animated:YES];
            break;
        }
    }
    //滚动到起始位置
    if (i >= self.conversationListDataSource.count) {
        //    self.conversationListTableView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
        for (i = 0; i < self.conversationListDataSource.count; i++) {
            RCConversationModel *model = self.conversationListDataSource[i];
            if (model.unreadMessageCount > 0) {
                NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:i inSection:0];
                self.index = i;
                [self.conversationListTableView scrollToRowAtIndexPath:scrollIndexPath
                                                      atScrollPosition:UITableViewScrollPositionTop animated:YES];
                break;
            }
        }
    }
}

- (void)updateForSharedMessageInsertSuccess{
    [self refreshConversationTableViewIfNeeded];
}

#pragma mark - UISearchBarDelegate
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    RCDSearchViewController *searchViewController = [[RCDSearchViewController alloc] init];
    self.searchNavigationController = [[UINavigationController alloc] initWithRootViewController:searchViewController];
    searchViewController.delegate = self;
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController.view addSubview:self.searchNavigationController.view];
}

- (void)onSearchCancelClick{
    [self.searchNavigationController.view removeFromSuperview];
    [self.searchNavigationController removeFromParentViewController];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.tabBarController.tabBar.hidden = NO;
    [self refreshConversationTableViewIfNeeded];
}

-(void)refreshCell:(NSNotification *)notify
{
    [self refreshConversationTableViewIfNeeded];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
